<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/7/25
 * Time: 10:27
 */

namespace App\Winged\Common\Controllers;


use App\Article;
use App\Category;
use App\Winged\Backend\Oss\OSS;
use App\Winged\Common\Service\MiPush;
use App\Winged\Components\Content;
use App\Winged\Patients\Service\Helpers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ArticleController extends BaseController
{
    const TYPE_TEMPLATE = 1 ; // 模板文章
    const TYPE_LINK = 2 ;  // 连接文章


    public function index()
    {
        return $this->Content(function(Content $content){
            $view = view('winged.common::article.index');
            return $content->body($view);
        });
    }

    public function getArticleList()
    {
        $tenant_id = tenant();
        $size = (int) request()->input("page_size",10);
        $page = (int) request()->input("page_index",0);
        $res = Article::where(['tenant_id' => $tenant_id])->with(['category' => function($query){
            $query->select("id","name");
        }])->orderBy("id","desc")->limit($size)->offset($page * 10)->get();
        $count =  Article::where(['tenant_id' => $tenant_id])->with(['category' => function($query){
            $query->select("id","name");
        }])->count();
        return response()->json(['status' => "SUCCESS" , 'data' => $res , 'total' => $count,'per_page' => $size]);
    }

    public function getCategory()
    {
        return response()->json(Category::all());
    }

    /**
     * 新增分类 | 修改分类
     */
    public function addCategory(Request $request)
    {
        $all = $request->all();
        if(isset($all['id'])) {
            $cate = Category::findOrFail($all['id']);
            $cate->name = isset($all['name']) ?? "" ;
            $cate->save();
            return response()->json(['status' => 1 , 'message' => '添加成功','data' => $cate ]);
        }
        else{
            $cate = new Category();
            if(!isset($all['name'])) {
                return response()->json(['status' => 0 , 'message' => '添加失败','data' => []]);
            }
            $cate->name = $all['name'];
            $cate->save();
            return response()->json(['status' => 1 , 'message' => '添加成功','data' => $cate ]);
        }
    }

    public function upload(Request $request)
    {
        try{
            $file = $request->file('file') ;
            $filename = Helpers::generateFileName($file);
            OSS::internelInstance()->setBucket(config('winged.backend.oss.article_bucket'));
            $res = OSS::publicUploadFile($filename,$file->path());
            return response()->json(internel2public($res));
        }catch (\Exception $e){
            return response()->json(['data'=>null],500);
        }
    }

    /**
     * 创建
     */
    public function create(Request $request)
    {
        try{
            $data = $request->all();
            // 如果是连接文章
            $article = new Article();
            $article->tenant_id = tenant();
            $article->category_id = $data ['category_id'];
            $is_push = isset($data ['is_push']) ? $data['is_push'] : 0 ;
            if($data['type'] == self::TYPE_LINK)
            {
                $article->content = json_encode($data ['content']);
                $res = $article->url = $data ['url'];
                $article->title = $data ['title'];
                $article->template = "";
                $article->type =  self::TYPE_LINK;
            }
            else{
                $res = $this->makeHtml($data);
                $article->content = json_encode($data ['content']);
                $article->url =  $res ;
                $article->title = $data ['title'];
                $article->template = $data['template'];
                $article->type =  self::TYPE_TEMPLATE;
            }
            if ($article->save()) {
                if($is_push == "1")
                {
                    $push = MiPush::push($article->title,$article->title,$article->toJson());
                }else{
                    $push = null;
                }
                return response()->json(['data' => $article, 'url' => $res , 'push' => $push]);
            } else {
                return response()->json(['data' => null], 200);
            }
        }
        catch (\Exception $exception){
            return response()->json(['data' => null , "message" => '提交数据格式错误::' .  $exception->getMessage()], 200);
        }

    }

    /**
     * @param Request $request更新
     */
    public function update(Request $request)
    {
        $data = $request->all();
        $article = Article::findOrFail($data ['id']);
        if($data['type'] == self::TYPE_TEMPLATE)
        {
            $data ['url'] = $article->url;
            $res = $this->makeHtml($data);
            $article->url = $res ;
        }
        else{
            $article->url = $data ['url'] ;
        }
        $article->content = json_encode($data ['content']);
        $article->template = isset($data['template']) ? $data['template'] : "";
        $article->title = $data ['title'];
        $article->category_id = $data ['category_id'];
        $article->save();
        return response()->json(['data' => $article,'url' => $article->url]);
    }

    /*
     *  head => {
     *     image => xxx ,
     *  }
     *  body =>[
     *  {
     *    title => xxx
     *    link  => xxx
     *  }
     * ]

     *
     */
    private function makeHtml($data)
    {
        $view = view("winged.common::article.template.template{$data['type']}",compact('data'));
        OSS::internelInstance()->setBucket(config('winged.backend.oss.article_bucket'));
        if(isset($data['url']) && !empty($data['url'])){
            $preg = '/^((http:\/\/)|(https:\/\/))?([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,6}(\/)/';
            $url = preg_replace($preg,"",$data['url']);
        }else{
            $url = Helpers::generateArticleName();
        }
        $res = OSS::publicUploadContent($url,$view->__toString());
        return internel2public($res) ;
    }

    /**
     * @router('/preview')
     * @param Request $request
     */
    public function preview(Request $request)
    {
        $data = $request->all();
        $template = "winged.common::article.template.template{$data['type']}";
        if(!view()->exists($template)){
            throw new \Exception("模板不存在::" . $template );
        }
        if(isset($data['content'])){
            $data ['content'] = json_decode($data ['content'],true);
        }
        return view($template,compact('data'));
    }
}
